﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Web;

namespace Tebbee.Business.Server.Common.Image
{
    public class ResizeImage
    {
        public static void ResizeImg(System.Drawing.Image Original, Int32 newWidth, Int32 newHeight, String pathToSave)
        {
            int sourceX = 0;
            int sourceY = 0;
            int destX = 0;
            int destY = 0;

            int originalWidth = Original.Width;
            int originalHeight = Original.Height;
            float nPercent = 0;
            float nPercentW = 0;
            float nPercentH = 0;

            nPercentW = ((float)newWidth / (float)originalWidth);
            nPercentH = ((float)newHeight / (float)originalHeight);

            if (nPercentH < nPercentW)
            {
                nPercent = nPercentH;
                destX = System.Convert.ToInt16((newWidth -
                              (originalWidth * nPercent)) / 2);
            }
            else
            {
                nPercent = nPercentW;
                destY = System.Convert.ToInt16((newHeight -
                              (originalHeight * nPercent)) / 2);
            }

            int destWidth = (int)(originalWidth * nPercent);
            int destHeight = (int)(originalHeight * nPercent);


            Bitmap bmp = new Bitmap(newWidth, newHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            bmp.SetResolution(Original.HorizontalResolution, Original.VerticalResolution);
            using (Graphics Graphic = Graphics.FromImage(bmp))
            {
                Graphic.CompositingQuality = CompositingQuality.HighQuality;
                Graphic.Clear(System.Drawing.Color.Transparent);
                Graphic.CompositingMode = CompositingMode.SourceCopy;
                Graphic.SmoothingMode = SmoothingMode.AntiAlias;
                Graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                Graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;

                Graphic.DrawImage(
                    Original,
                    new System.Drawing.Rectangle(destX, destY, destWidth, destHeight),
                    new System.Drawing.Rectangle(sourceX, sourceY, originalWidth, originalHeight),
                    GraphicsUnit.Pixel
                    );

                bmp.Save(pathToSave, Original.RawFormat);

            }

        }
    }
}